package com.work.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.work.common.enums.UserClockRecordType;
import com.work.common.enums.UserClockType;
import com.work.common.exp.WorkException;
import com.work.entity.UserClock;
import com.work.mapper.UserClockMapper;
import com.work.service.UserClockService;
import com.work.service.UserLoginService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserClockServiceImpl extends ServiceImpl<UserClockMapper, UserClock> implements UserClockService {
    private final UserLoginService userLoginService;

    //    基础表达式抽离
    private QueryWrapper<UserClock> expression(String dateFiled, String date) {
        Long userId = 1L;
//        校验用户是否存在
        userLoginService.userExistById(userId);
        return Wrappers.query(UserClock.class)
                .eq("user_id", userId)
                .eq(dateFiled, date);
    }

    //    获取用户当天打卡状态
    public boolean getUserClockStatus(int status) {
        final QueryWrapper<UserClock> queryWrapper = expression("DATE_FORMAT(clock_time,'%Y-%m-%d')", LocalDate.now().toString())
                .eq("clock_status", status);
        return super.exists(queryWrapper);
    }

    @Override
    public Boolean userClock() {
//        获取用户id
//        AuthUtil.getRequest()  //这个工具用来解析前端的token从而获取用户id
//        这里假设有一个用户id
        long userId = 1L;
//        校验用户是否存在
        userLoginService.userExistById(userId);

        UserClock saveUserClock = new UserClock();
        saveUserClock.setUserId(userId);
        saveUserClock.setClockTime(LocalDateTime.now());
        saveUserClock.setRecordTime(LocalDateTime.now());

        try {
            final boolean record = getUserClockStatus(UserClockType.WORK.getCode());
            if (!record) {
                saveUserClock.setClockStatus(UserClockType.WORK.getCode());
                return super.save(saveUserClock);
            }
            final boolean over = getUserClockStatus(UserClockType.WORK_OVER.getCode());
            if (over) {
                throw new WorkException(10033, "已经打卡下班了");
            }
            saveUserClock.setClockStatus(UserClockType.WORK_OVER.getCode());
            return super.save(saveUserClock);
        } catch (Exception e) {
            log.error("打卡失败", e);
            throw new WorkException(10031, "打卡失败");
        }
    }

    @Override
    public List<UserClock> getUserClockRecord(LocalDateTime date, UserClockRecordType userClockRecordType) {
        return super.list(expression(userClockRecordType.getFn().apply("clock_time"), userClockRecordType.getDate().apply(date)));
    }

    @Override
    public List<UserClock> getUserClockRecord(LocalDateTime date) {
        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        QueryWrapper<UserClock> queryWrapper = expression("DATE_FORMAT(clock_time,'%Y-%m')", date.format(formatter))
                .eq("clock_status", UserClockType.UN_CLOCK.getCode());
        return super.list(queryWrapper);
    }

    @Override
    public long getUserUnClockCount(LocalDate date) {
        QueryWrapper<UserClock> queryWrapper = expression("YEAR(clock_time)", String.valueOf(date.getYear()))
                .eq("clock_status", UserClockType.UN_CLOCK.getCode());
        return super.count(queryWrapper);
    }
}
